<template>
	<div class="home-page">
		<div class="select-cascader">
			<a-select class="cascader" v-model:value="address" show-search placeholder="请选择区域" style="width:100%"
				:options="options" :filter-option="filterOption" @change="handleChange"></a-select>
		</div>
		<HomeLeft ref='child' :address="address" :KspMapclass="KspMapclass"></HomeLeft>
		<!-- <HomeMap @mapClick="mapClick"></HomeMap> -->
		<div class="hompage" id="map">
			<OlMap ref="dialog" @updatemap="updatemap"></OlMap>
		</div>
		<HomeRight ref="homerightRef"></HomeRight>
		<div class="gohome" @click="gohome()">
			<i class="Ticonfont Ticon-fuwei"></i>
		</div>
		<div ref="msgForm" class="msgForm">
			<h1>简介</h1>
			<p v-if="companyInfo.desc">{{ companyInfo.desc }}</p>
			<p v-else> <a-empty description="暂无数据" /></p>
		</div>

		<div class="collect-top">
			<div class="collect-header">
				万载农业产值表
			</div>
			<div class="collect-list">
				<div class="collect-item">
					<div class="collect-title">累计收入</div>
					<div class="price">{{statistics.all}}元</div>
				</div>
				<div class="collect-item">
					<div class="collect-title">年收入</div>
					<div class="price">{{statistics.year}}元</div>
				</div>
				<div class="collect-item">
					<div class="collect-title">月收入</div>
					<div class="price">{{statistics.month}}元</div>
				</div>
				<div class="collect-item">
					<div class="collect-title">日收入</div>
					<div class="price">{{statistics.day}}元</div>
				</div>
			</div>

		</div>
	</div>
</template>
<script setup>
import HomeLeft from './home-left.vue'
// import HomeMap from './home-map.vue'
import HomeRight from './home-right.vue'
import muajax from '/src/common/axios-core-mu.js'
import OlMap from "@/components/map/olMap.vue";
import {
	onUnmounted,
	onMounted,
	ref
} from "vue";
import KspMap from "@/components/map/utils/kspmap";
import $ from "jquery";
import {
	Circle,
	LinearRing
} from "ol/geom";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Style from "ol/style/Style";
import Stroke from "ol/style/Stroke";
import Fill from "ol/style/Fill";
import {
	GeoJSON
} from "ol/format";
import {
	boundingExtent
} from "ol/extent";
import Text from "ol/style/Text";
import {
	Feature
} from "ol";

import Overlay from "ol/Overlay"
import {
	fromExtent
} from "ol/geom/Polygon";
import Mask from 'ol-ext/filter/Mask'
import Crop from 'ol-ext/filter/Crop'
import 'ol-ext/dist/ol-ext.min.css';
import _ from 'lodash'

let KspMapclass;
let dialog = ref();
let updateMapdata = null;
let geojsonLayer = null
let featuresList = []//全部features

let onfeature = new Feature() //选中的图层
let masklayer = null //蒙版图层
let wmsLayer = null
let lineLayer = null
let innerLayer = null //边框图层
let outerLayer = null //外框图层
let iszoom = false
let child = ref();  // 子组件
const options = ref([]);
const statistics = ref({});
const address = ref('');
const msgForm = ref();
// onMounted(() => {
// 	window.myEventListen_click1 = initaddress()
// });
muajax.getaddress().then((res) => {
	options.value = res.data.list
})

// 提交一个倒计时
const timerHanlde = () => {
	muajax.statistics().then((res) => {
		statistics.value = res.data.data
	})
};

let timer = setInterval(timerHanlde, 5000)
onUnmounted(() => {
	clearInterval(timer)
});






const handleChange = value => {
	address.value = value;
	console.log(`selected ${value}`);

};
const handleBlur = () => {
	console.log('blur');
};
const handleFocus = () => {
	console.log('focus');
};

const filterOption = (input, option) => {
	console.log("地区", input);
	let b = option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
	return b
};

// 地图点击
function regionClick(e) {
	if (e) {
		// console.log("地区", e.regionFeature.values_.id);
		if (e.regionFeature) {
			let area_no = e.regionFeature.values_ ? e.regionFeature.values_.id : null
			address.value = area_no ? options.value.filter(v => v.area_no == area_no)[0].value : null

		}

	}
}

let layervectorSource = new VectorSource({
	format: new GeoJSON(),
});
// 线图层
// onMounted(() => { });
// const emit = defineEmits(["mapClick"]);
function updatemap(map) {
	if (map) {
		updateMapdata = map;
		KspMapclass = new KspMap(updateMapdata);
		KspMapclass.addMapEvent('singleclick', (e) => {
			mapclick(e)
		})
		updateMapdata.on('pointermove', mapPointermove)
		updateMapdata.getView().on('change:resolution', () => {
			bounce()
		})
		initLayer()//初始化图层
		wmsHoverLayer()
		wfsPolygon()
		setTimeout(() => {
			handleChange(null)
		}, 1000)

	}
}
// 防抖
let bounce = _.debounce(function () {
	let zoom = updateMapdata.getView().getZoom()
	if (iszoom && zoom < 11) {
		iszoom = false
		// outerLayer && outerLayer.getSource().clear()
		gohome()
	}
}, 1000)
// 回到初始地图状态
function gohome() {
	layervectorSource.clear()
	regionClick({ regionFeature: 1 })
	// emit("mapClick", {regionFeature:1});
	wfsPolygon()
}


function mapclick(event) {
	if (event && event.regionFeature) {
		onfeature = event.regionFeature
		outerLayer && outerLayer.getSource().clear()
		outerLayer.getSource().addFeature(onfeature)
		iszoom = true
		let extent = event.regionFeature.getGeometry().getExtent()
		updateMapdata.getView().fit(extent, {
			size: updateMapdata.getSize(),
			padding: [150, 150, 150, 150],
			duration: 800,
		}); //居中到geometry视野中
		regionClick(event);
	} else if (event && event.data && event.data.id) {
		// companyid.value=event.data.id
		console.log(event.data.id, 111111111111)
		child.value.infoChange({ id: event.data.id })
	}
}


let companyInfo = ref({})
//鼠标移动
function mapPointermove(event) {
	geojsonLayer && geojsonLayer.getSource().clear()
	let feature = updateMapdata.forEachFeatureAtPixel(
		event['pixel'],
		(feature) => {
			return feature
		}
	)
	if (feature) {
		options.value.forEach((item) => {
			console.log(item)
			if (item.area_no == feature.values_.id) {
				companyInfo.value = item
			}
		})
		geojsonLayer.getSource().addFeature(feature)
		addHoverInteraction(feature)
	} else {
		addHoverInteraction(null)
	}

	// console.log(feature);
}


/**
  * 添加hover交互
  * @param layer
  */
function addHoverInteraction(feature) {
	if (feature) {
		// let props = feature.getProperties()
		setMapToolTip()
	} else {
		removeToolTip()
	}
}

/**
 * 处理tooltip-overlay的位置
 * @param event
 */
function mapTooltip(event) {
	console.log(event.position)
	console.log(helpTooltip)
	if (helpTooltip) {
		helpTooltip.setPosition(event['position'])
	}
}
/**
 *
 * @param props feature上的props
 */
function setMapToolTip(props) {
	// updateMapdata.on('pointermove', mapTooltip)
	updateMapdata.on('pointermove', mapTooltip)
	if (!helpTooltip) {
		helpTooltip = new Overlay({
			stopEvent: true,
			// element: msgForm.value,// msgForm.value
			offset: [15, 0],
			positioning: 'center-left',
			zIndex: 1000,
		})
		helpTooltip.setElement(msgForm.value)
		//  helpTooltip = new ol.Overlay({
		//     stopEvent: true,
		//     offset: [15, 0],
		//     positioning: 'center-left',
		//   })
		updateMapdata.addOverlay(helpTooltip)
		updateMapdata.on('pointermove', mapTooltip)
	}
}
function removeToolTip() {
	if (helpTooltip) {
		helpTooltip.setPosition(undefined)
		helpTooltip = null
		updateMapdata.removeOverlay(helpTooltip)
		updateMapdata.on('pointermove', mapTooltip)
	}
}

// 鼠标移动的图层
function wmsHoverLayer() {
	// 鼠标移动上去的图层
	geojsonLayer = new VectorLayer({
		source: new VectorSource(),
		zIndex: 1,
		zIndex: 99,
		style: new Style({
			stroke: new Stroke({
				color: 'red',
				// lineDash: [4],
				width: 1,
			}),
			fill: new Fill({
				color: 'rgba(255,0,0, 0.5)',
			}),
		}),
	})
	updateMapdata.addLayer(geojsonLayer)
}

let overlayForm
let helpTooltip
// 初始化图层
function initLayer() {
	wmsLayer = new VectorLayer({
		source: layervectorSource,
		zIndex: 15,
		style: (feature) => {
			let text = feature.get("name");
			return new Style({
				// }),
				fill: new Fill({
					color: 'rgba(12, 96, 80, 0.65)',
				}),
			})
		}
	})
	updateMapdata.addLayer(wmsLayer);
	lineLayer = new VectorLayer({
		source: layervectorSource,
		zIndex: 999,
		style: (feature) => {
			let text = feature.get("name");
			return new Style({
				stroke: new Stroke({
					color: 'rgba(12, 96, 80, 1)',
					width: 1,
				}),
				text: new Text({
					text: text,
					font: '14px Calibri,sans-serif',
					fill: new Fill({
						color: '#fff',
					}),
					stroke: new Stroke({
						color: 'rgba(40,120,255, 0.5)',
						width: 3,
					}),
				}),
			})
		}
	})
	updateMapdata.addLayer(lineLayer);
	innerLayer = new VectorLayer({
		source: layervectorSource,
		style: new Style({
			stroke: new Stroke({
				width: 10,
				color: 'rgba(255,255,255, 0.4)'
			}),
			fill: new Fill({
				color: 'rgba(40,120,255, 0)'
			})
		}),
		zIndex: 2
	});
	updateMapdata.addLayer(innerLayer);
	outerLayer = new VectorLayer({
		source: layervectorSource,
		style: new Style({
			stroke: new Stroke({
				width: 5,
				color: 'rgba(255,255,255, 0.4)'
			}),
			fill: new Fill({
				color: 'rgba(40,120,255, 0)'
			})
		}),
		zIndex: 2
	});
	updateMapdata.addLayer(outerLayer);
	masklayer = new VectorLayer({
		source: new VectorSource(),
		style: new Style({
			fill: new Fill({
				color: 'rgba(40,120,255, 0.8)',
			}),
			stroke: new Stroke({
				color: 'transparent',
			}),
		}),
		zIndex: 11,
	})
	updateMapdata.addLayer(masklayer)

}

// 查询行政区划线

function wfsPolygon() {
	let url = '/api/Address/addressjson'
	layervectorSource.clear()
	$.ajax({
		type: "GET",
		url: url,
		success: (res) => {
			let result = JSON.parse(res);
			let coordinates = [];
			for (let f of result["features"]) {
				let feature = new GeoJSON().readFeatures(f);
				if (feature[0].getGeometry()) {

					let geom = feature[0]
						.getGeometry()
						.transform("EPSG:4326", "EPSG:3857");
					feature[0].setGeometry(geom);
					layervectorSource.addFeatures(feature);
					featuresList.push(feature);
					const extents = geom.getExtent();
					coordinates.push(
						[extents[0], extents[1]],
						[extents[2], extents[3]]
					);

				}
			}
			extent = boundingExtent(coordinates);
			updateMapdata.getView().fit(extent, {
				size: updateMapdata.getSize(),
				padding: [150, 150, 150, 150],
				duration: 800,
			}); //居中到geometry视野中
			console.log(featuresList);

			// addMask(result)
		},
		error: function (jq) {
			console.log("失败", jq);
		},
	});

	let extent = null;

	let f = new GeoJSON().readFeature(require('@/assets/360922.json').features[0])
	var mask = new Mask({
		feature: f,
		wrapX: true,
		inner: false,
		fill: new Fill({
			color: [0, 0, 0, 0]
		})
	});
	var crop = new Crop({
		feature: f,
		wrapX: true,
		inner: false
	});
	// 若不加天地图就直接将osmlayer 使用addFilter 就行

	masklayer.addFilter(crop);
	masklayer.addFilter(mask);


}


// 添加蒙版
function addMask(featureGeometry) {
	masklayer.getSource().clear()
	let vectorSource = new VectorLayer({
		features: [
			new Feature({
				geometry: erase(featureGeometry),
			}),
		],
	})
	masklayer.setSource(vectorSource)

}

function erase(geom) {
	const extent = [-180, -90, 180, 90];
	const polygonRing = fromExtent(extent);
	const coords = geom.getCoordinates();
	coords.forEach(coord => {
		const linearRing = new LinearRing(coord[0]);
		polygonRing.appendLinearRing(linearRing);
	});
	return polygonRing;
}


/**
 * 清除图层
 */
function claer() {
	KspMapclass.removeVectorLayer("areas_v3");
	KspMapclass.deleteAllDrawFeature()
}






</script>
<style lang="less" scoped>
@import "@/assets/css/minxin.less";
@vw: 0.05208vw;
/deep/ .a-layout-content{
	min-width: 1440px;
    margin: 0px auto;
}
.home-page {
	width: 100%;
	height: 100%;
	// background-color: #f5f5f5;
	display: flex;
	color: #fff;
	// background: red;
	// background: url('../assets/images/bg.jpg') no-repeat;

	background: url("@/assets/images/bj.jpg") no-repeat;
	background-size: 100% 100%;
	position: relative;
	min-width: 1440px;
}

.select-cascader {
	position: absolute;
	left: 400px;
	top: 23px;
	width: 200*0.05208vw;
	z-index: 999;

	.cascader {
		box-shadow: 0px 0px 30px 0px rgba(20, 235, 166, 0.5) inset;
		border-radius: 5px;
		background: rgba(6, 61, 56, 0.7);
		height: 100%;
		border: 1px solid rgba(11, 160, 113, 1);

		.ant-select-selector {
			background: none;

		}
	}
}

/deep/ .select-cascader .ant-select-selector {
	background: none;
	color: #fff;

	.ant-select-selection-placeholder {
		color: #ccc;
	}

	.ant-select-selection-search-input {
		&::-ms-input-placeholder {
			color: #ccc;
		}

		&:-moz-placeholder {
			color: #ccc;
		}

		&::-moz-placeholder {
			color: #ccc;
		}

		&::-webkit-input-placeholder {
			color: #ccc;
		}

		&:-ms-input-placeholder {
			color: #ccc;
		}
	}

}

/deep/ .ant-select .ant-select-arrow {
	color: #fff
}

.gohome {
	position: absolute;
	right: 400px;
	bottom: 100px;
	width: 50px;
	height: 50px;
	background: #0D3839;
	border: 1px solid #0E7D60;
	border-radius: 5px;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;

	.Ticonfont {
		color: #0E7D60;
		font-size: 36px;
	}
}

.msgForm {
	width: 330px;
	min-height: 243px;
	background: rgba(6, 61, 56, 0.5);
	border: 1px solid #0E7D60;
	box-shadow: 0px 0px 18px 0px rgba(20, 235, 166, 0.5) inset;
	border-radius: 5px;
	// overflow-y: scroll;
	padding: 10px;
	box-sizing: border-box;
	// opacity: 0;
	// position: relative;
	// z-index: 1000000;
	// .gray-scroll-bar();
}


.collect-top{
    overflow-y: auto;
    // width: 354px;
    background: rgba(6, 61, 56, 0.7);
    border: 1px solid #0e7d60;
    box-shadow: 0px 0px 10px 0px rgba(20, 235, 166, 0.5) inset;
    border-radius: 5px;
    padding: 14px;
    box-sizing: border-box;
	position: absolute;
	top: 20px;
	left: 50%;
	transform: translate(-50%, 0);
	.collect-header{
		text-align: center;
		// line-height: 40px;
		margin-bottom: 15px;
		font-size:28px;
	}
	.collect-list{
		display: flex;
		align-items: center;
		.collect-item{
			position: relative;
			width: 100*0.05208vw;
			text-align: center;
			.collect-title{
				margin-bottom: 5px;
			}
			&::after{
				content: '';
				position: absolute;
				right: 0px;
				bottom: 0px;
				height: 40px;
				opacity: 0.5;
				width: 1px;
				background: #fff;
			
			}
			&:nth-last-child(1){
				&::after{
					opacity: 0;
				}
			}
		}
		.price{
			color: rgba(39, 251, 64, 1);
		}
	}
}
</style>       